class PostsController < ApplicationController  

  before_filter :tag_clouds, :only => [:index, :show, :tag, :search]
  
  
  def index
     unless params[:q].blank?
       @posts = Post.find_fulltext(params[:q])       
     else
       @posts = Post.find(:all, :page =>{:size => 10, :current => params[:page]}, :order=> "published_at DESC")
     end
     show_small_map(@posts) 
  end

  def list
     unless params[:tag].blank?
       @posts = Post.find_tagged_with(params[:tag])
     else
       @posts = Post.find(:all)
     end
     
    render :layout => false
  end

 
  
  def show
    @post = Post.find(params[:id])
    show_small_map([@post])
  end

  def tag    
    @posts = Post.find_tagged_with(params[:id])
    show_small_map(@posts)
  end

  def edit
    redirect_to :action => "index" unless logged_in?    
    @post = Post.find(params[:id])

    render :layout => "layouts/admin"
  end

  def update
    post = Post.find(params[:id])
    post.update_attributes!(params[:post])
    
    redirect_to :action => "index"
  end

  def destroy
    if logged_in?
      post = Post.find(params[:id])
      post.destroy
    end
    redirect_to :action => "index"
  end
  
  private
  def tag_clouds
    @tags = Tag.tags(:limit => 100, :order => "name desc")
  end

  def show_small_map(posts)    
    @map = GMap.new("map_div")
    @map.control_init(:large_map => false, :map_type => false)
    
    coords = []  
    posts.each do |post|
      post.geotags.each do |geotag|
        coords << [geotag.latitude, geotag.longitude]
      end
    end
    if coords.length > 0  
      @map.center_zoom_init(coords[0],5)
      coords.each {|coord| @map.overlay_init(GMarker.new(coord,:title => ""))}  
    else
      @map.center_zoom_init([0,0],0)
    end
      
    
  end
  
end
